package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/region")
public class RegionController {

    @Autowired
    public IRegionService regionService;

    //只作视图跳转
    @RequestMapping("/list")
    public String list() {
        return "region/list";
    }


    @RequestMapping("/listByParentId")
    @ResponseBody
    public List listByParentId(Long parentId,String type) {

        List<Region> regions = regionService.selectByParentId(parentId);
        //为什么要用新的list去接收呢? 而不是直接 遍历取值
        //因为要存储成treeview格式的map
        if("tree".equals(type)) {

            ArrayList<Object> treeList = new ArrayList<>();
            for (Region region : regions) {
                treeList.add(region.ToTreeMap());
            }
            return treeList;
        }
        return regions;

    }

    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public JsonResult update(Region region){
        JsonResult jsonResult = new JsonResult();
        if(region.getId() != null){
            regionService.updateByPrimaryKey(region);
        }else {
            regionService.insert(region);
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping("/changeState")
    public String changeStatus(Long id,Integer state){

        regionService.updateStatus(id,state);
        return "redirect:/region/list";
    }
}
